<template>
  <div>
    <div v-if="brands && brands.length">
      <h2>品牌占比</h2>
      <v-chart class="chart" :option="brandOption"></v-chart>
    </div>
    <div v-else>
      <p>加载中...</p>
    </div>
    <div v-if="priceDistribution && priceDistribution.length">
      <h2>各品牌价格分布散点图</h2>
      <v-chart class="chart" :option="scatterOption"></v-chart>
    </div>
    <div v-else>
      <p>加载中...</p>
    </div>
    <div v-if="commentCount">
      <h2>各品牌评论统计（求自然对数后）</h2>
      <v-chart class="chart" :option="barOption"></v-chart>
    </div>
    <div v-else>
      <p>加载中...</p>
    </div>
  </div>
</template>

<script>
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import VChart from "vue-echarts"
import {
  PieChart,
  ScatterChart
} from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  DatasetComponent,
  VisualMapComponent,
  GridComponent,
  TransformComponent
} from 'echarts/components'
use([
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  PieChart,
  CanvasRenderer,
  DatasetComponent,
  VisualMapComponent,
  GridComponent,
  TransformComponent,
  ScatterChart
])

export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name: 'About',
  components: {
    VChart
  },
  data() {
    return {
      brands: [],
      priceDistribution: [],
      commentCount: {},
      brandMap: {},
      brandOption: {
        title: {
          text: '品牌排名数量占比',
          left: 'center'
        },
        tooltip: {
          trigger: 'item'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [
          {
            name: '品牌',
            type: 'pie',
            radius: ['40%', '70%'],
            data: [],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      },
      scatterOption: {
        legend: {
          data: []
        },
        xAxis: {
          splitLine: {
            lineStyle: {
              type: 'dashed'
            }
          }
        },
        yAxis: {
          splitLine: {
            lineStyle: {
              type: 'dashed'
            }
          }
        },
        tooltip: {
          position: 'top'
        },
        series: []
      },

      barOption: {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: ['好评', '中评', '差评']
        },
        toolbox: {
          show: true,
          orient: 'vertical',
          left: 'right',
          top: 'center',
          feature: {
            mark: {show: true},
            dataView: {show: true, readOnly: false},
            magicType: {show: true, type: ['line', 'bar', 'stack', 'pie']},
            saveAsImage: {show: true}
          }
        },
        xAxis: [
          {
            type: 'category',
            axisTick: {show: false},
            data: []
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: [
          {
            name: '好评',
            type: 'bar',
            barGap: 0,
            emphasis: {
              focus: 'series'
            },
            data: []
          },
          {
            name: '中评',
            type: 'bar',
            emphasis: {
              focus: 'series'
            },
            data: []
          },
          {
            name: '差评',
            type: 'bar',
            emphasis: {
              focus: 'series'
            },
            data: []
          }
        ]
      }
    }
  },
  mounted() {
    this.fetchBrandCounts();
    this.fetchPriceDistribution();
    this.fetchCommentCount();
  },
  methods: {
    // 设置散点图series
    setScatterSeries() {
      this.scatterOption.legend.data = Object.keys(this.brandMap)

      // 设置散点图的series
      Object.keys(this.brandMap).forEach(brand => {
        this.scatterOption.series.push({
          name: brand,
          data: this.brandMap[brand].map(item => [item.rank, item.price]),
          type: 'scatter',
          symbolSize: 15
        })
      })
    },

    setBarSeries() {
      let xAxisData = []
      let comments = {
        good: [],
        middle: [],
        bad: []
      }
      this.commentCount.forEach(item => {
        xAxisData.push(item.brand)
        comments.good.push(Math.log(item.goodCount))
        comments.middle.push(Math.log(item.middleCount))
        comments.bad.push(Math.log(item.badCount))
      })

      this.barOption.xAxis[0].data = xAxisData
      // 设置柱状图的series
      this.barOption.series[0].data = comments.good
      this.barOption.series[1].data = comments.middle
      this.barOption.series[2].data = comments.bad
    },

    // 获取品牌排名数量占比
    async fetchBrandCounts() {
      try {
        const response = await fetch('http://127.0.0.1:5000/brand_count');
        const result = await response.json();
        if (result.code === 200) {
          const brands = Object.keys(result.data).map(brand => ({
            value: result.data[brand].count,
            name: brand
          }));
          this.brands = brands;
          this.brandOption.series[0].data = brands
        } else {
          console.error('Failed to fetch brand counts:', result.message);
        }
      } catch (error) {
        console.error('Error fetching brand counts:', error);
      }
    },

    // 获取价格分布
    async fetchPriceDistribution() {
      try {
        const response = await fetch('http://127.0.0.1:5000/priceDistribution');
        const result = await response.json();
        if (result.code === 200) {
          this.priceDistribution = result.data;

          this.priceDistribution.forEach(item => {
            const brand = item.brand;
            const rank = item.rank;
            const price = item.price;
            if (!this.brandMap[brand]) {
              this.brandMap[brand] = [];
            }
            this.brandMap[brand].push({rank, price});
          });
          this.setScatterSeries()
        } else {
          console.error('Failed to fetch price distribution:', result.message);
        }
      } catch (error) {
        console.error('Error fetching price distribution:', error);
      }
    },

    // 获取好中差评数量
    async fetchCommentCount() {
      try {
        const response = await fetch('http://127.0.0.1:5000/get_reviews_summary');
        const result = await response.json();
        if (result.code === 200) {
          this.commentCount = result.data
          this.setBarSeries()
        } else {
          console.error('Failed to fetch comment count:', result.message);
        }
      } catch (error) {
        console.error('Error fetching comment count:', error);
      }
    }
  }
}
</script>

<style scoped>
h1 {
  font-size: 24px;
  margin-bottom: 16px;
}
h2 {
  font-size: 20px;
  margin-top: 24px;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  font-size: 16px;
  margin: 8px 0;
}
p {
  font-size: 16px;
}
.chart {
  height: 400px;
}
</style>
